package com.cg.utils;

import com.cg.entity.TokenInfo;
import com.cg.entity.WeChatUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

@Slf4j
public class WechatUtil {

    public static final String APP_ID = "wx1374ae9c3adb0e3f";
    public static final String APP_SECRET = "ae0557ec078fbdba0342778e254f2c71";

    private WechatUtil() {
    }

    public static WeChatUser getUserInfo(String code) throws IOException {
        //构造http请求客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //用code交换token，code为扫描后微信服务器相应来的授权码
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code";
        //发请求
        HttpGet httpGet = new HttpGet(tokenUrl);
        String responseResult = "";
        //接受返回的数据，转成utf-8格式
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info("获取accessToken返回结果:{}", responseResult);

        //将结果封装到TokenInfo中
        TokenInfo tokenInfo = new ObjectMapper().readValue(responseResult, TokenInfo.class);

        //用accessToken获取扫码人的个人信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenInfo.getAccess_token() + "&openid=" + tokenInfo.getOpenid() + "&lang=zh_CN";
        //构造http请求客户端
        HttpGet httpGet1 = new HttpGet(userInfoUrl);
        //接收数据
        HttpResponse response1 = httpClient.execute(httpGet1);
        if (response1.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(response1.getEntity(), "UTF-8");
        }
        log.info("返回用户信息结果:{}", responseResult);
        //将结果封装到WeChatUser对象中
        return new ObjectMapper().readValue(responseResult, WeChatUser.class);
    }
}
